<template>
  <el-container>
    <el-main class="main-bg">
      <el-form ref="searchForm" :model="searchForm" label-width="100px">
        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="计划名称">
              <el-input
                v-model="searchForm.planName"
                placeholder="请输入计划名称"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="计划抽选时间">
              <el-date-picker
                v-model="createdTime"
                end-placeholder="结束日期"
                placeholder="选择日期"
                range-separator="至"
                start-placeholder="开始日期"
                style="width: 100%"
                type="daterange"
                value-format="yyyy-MM-dd"
                @change="onTimeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作员姓名">
              <el-select
                v-model="searchForm.checkMan1"
                placeholder="请选择操作员"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.userCode"
                  :label="item.userName"
                  :value="item.userName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="监督员姓名">
              <el-select
                v-model="searchForm.checkMan2"
                placeholder="请选择监督员"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.userCode"
                  :label="item.userName"
                  :value="item.userName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="text-right">
            <el-button
              icon="iconfont iconxianxing_sousuo"
              type="primary"
              @click="handleSearch"
            >
              查询
            </el-button>
            <el-button
              icon="iconfont iconxianxing_zhongzhi"
              @click="handleReset"
            >
              重置
            </el-button>
          </el-col>
          <el-col v-if="userInfo.role !== '2'" :span="24" class="text-left">
            <el-button type="primary" @click="onAdd">
              新增抽选计划
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <Table
        ref="table"
        :current-page="page"
        :header-data="tableHeader"
        :index="false"
        :loading="loading"
        :page-size="limit"
        :table-data="tableData"
        :total="total"
        class="data-table"
        style="width: 100%"
        border
        @now-page="handlePage"
        @now-size="handleSize"
        @table-sort="handleSort"
      />
    </el-main>
    <el-drawer
      :title="title"
      :visible.sync="drawerVisible"
      :wrapper-closable="false"
    >
      <div class="drawer-main">
        <el-form ref="form" :model="form" :rules="rules" label-position="top">
          <el-form-item label="计划名称" prop="planName" required>
            <el-input v-model="form.planName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="计划抽选时间" prop="planDate" required>
            <el-date-picker
              v-model="form.planDate"
              type="date"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              style="width: 100%;"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              placeholder="请输入"
              type="textarea"
            />
          </el-form-item>
        </el-form>
      </div>
      <div v-if="type !== 'look'" class="drawer-footer">
        <div class="footer-btn">
          <el-button type="primary" @click="handleSubmit"> 确认</el-button>
          <el-button @click="onCancel"> 取消</el-button>
        </div>
      </div>
    </el-drawer>

    <el-dialog title="身份信息确认" :visible.sync="dialogVisible" width="500px">
      <el-form
        ref="dialogForm"
        :model="dialogForm"
        label-position="top"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="userName" required>
          <el-input
            v-model="dialogForm.userName"
            autocomplete="off"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="password" required>
          <el-input
            v-model="dialogForm.password"
            autocomplete="off"
            placeholder="请输入确认密码"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ondialogCancel">取 消</el-button>
        <el-button type="primary" @click="dialogSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="选择所属库" :visible.sync="kuDialogVisible" width="500px">
      <el-form
        ref="kuDialogForm"
        :model="kuDialogForm"
        label-position="top"
        :rules="kuRules"
      >
        <el-form-item label="所属库" prop="warehouseId" required>
          <el-select
            v-model="kuDialogForm.warehouseId"
            placeholder="请选择"
            clearable
            @change="onChange"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="kuDialogCancel">取 消</el-button>
        <el-button type="primary" @click="kuDialogSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import addTable from "@/mixins/addtable";
import {
  getPlanList,
  postPlanDel,
  postPlanAdd,
  postPlanUpdate,
  postPlanCheck,
} from "./api";
import { parseTime } from "@/utils";
import { mapGetters } from "vuex";
import { getExtractFindById } from "../extract/api";
import { getWarehouseList } from "../warehouse/api";
import selectMinx from "../mixins/index";

export default {
  name: "PlanList",
  mixins: [addTable, selectMinx],
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now() - 8.64e7;
        },
      },
      warehouseList: [],
      searchForm: {
        planName: "",
        checkMan1: "",
        checkMan2: "",
        planDate: [],
      },
      createdTime: null,
      title: "",
      type: "look",
      tableHeader: [],
      personOptions: [],
      oneLoading: false,
      drawerVisible: false,
      dialogVisible: false,
      kuDialogVisible: false,
      form: {
        planId: "",
        planName: "",
        planDate: "",
        remark: "",
      },
      dialogForm: {
        planId: "",
        userName: "",
        password: "",
        status: "",
      },
      kuDialogForm: {
        warehouseId: "",
        warehouseName: "",
        planId: "",
        planName: "",
      },
      rules: {
        planName: [{ required: true, message: "计划名称必填" }],
        planDate: [{ required: true, message: "计划抽选时间必填" }],
        userName: [{ required: true, message: "用户名称必填" }],
        password: [{ required: true, message: "确认密码必填" }],
      },
      kuRules: {
        warehouseId: [
          { required: true, message: "所属库必选", tirger: "change" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  created() {
    this.tableHeader = [
      {
        prop: "planName",
        label: "计划名称",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "planDate",
        label: "计划抽选时间",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "checkMan1",
        label: "操作员",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "checkTime1",
        label: "操作员验证时间",
        sortable: false,
        overflow: true,
        align: "left",
        width: 180,
        render: (h, vm) => {
          const time = vm.checkTime1 ? parseTime(vm.checkTime1) : "";
          return <span>{time}</span>;
        },
      },
      {
        prop: "checkMan2",
        label: "监督员",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "checkTime2",
        label: "监督员验证时间",
        sortable: false,
        overflow: true,
        align: "left",
        width: 180,
        render: (h, vm) => {
          const time = vm.checkTime2 ? parseTime(vm.checkTime2) : "";
          return <span>{time}</span>;
        },
      },
      {
        prop: "status",
        label: "状态",
        sortable: false,
        overflow: true,
        align: "left",
        render(h, vw) {
          if (vw.status === 0) {
            return <el-tag>未确认</el-tag>;
          } else if (vw.status === "1") {
            return <el-tag type='danger'>可以抽选</el-tag>;
          } else if (vw.status === "2") {
            return <el-tag type='warning'>监督员已经确认</el-tag>;
          } else if (vw.status === "3") {
            return <el-tag type='warning'>操作员已经确认</el-tag>;
          } else if (vw.status === "0") {
            return <el-tag type='info'>暂未确认</el-tag>;
          } else if (vw.status === "4") {
            return <el-tag type='success'>已抽选</el-tag>;
          }
        },
      },
      {
        prop: "remark",
        label: "备注",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        width: 150,
        label: "操作",
        align: "left",
        fixed: "right",
        buttonList: (row, index) => {
          const arr = [];
          const isAdmin = this.userInfo.role === "1";
          const isStatus1 = row.status === "1";
          const isStatus4 = row.status === "4";

          if (isAdmin) {
            arr.push({
              text: isStatus1 ? "抽选" : isStatus4 ? "打印" : "编辑",
              type: "text",
              event: isStatus1
                ? this.onExtract
                : isStatus4
                ? this.onDetail
                : this.onEdit,
            });
            arr.push({
              text: "删除",
              type: "text",
              event: this.onDelete,
            });
          } else {
            arr.push({
              text: isStatus1 ? "抽选" : isStatus4 ? "打印" : "身份认证",
              type: "text",
              event: isStatus1
                ? this.onExtract
                : isStatus4
                ? this.onDetail
                : this.onConfirm,
            });
          }
          return arr;
        },
      },
    ];

    this.getTableData();
  },

  methods: {
    onTimeChange(date) {
      if (date) {
        const dateMin = date[0] + " 00:00:00";
        const dateMax = date[1] + " 23:59:59";
        const timestampMin = new Date(dateMin).getTime();
        const timestampMax = new Date(dateMax).getTime();
        this.searchForm.planDate = [timestampMin, timestampMax];
      }
    },
    onChange(id) {
      this.kuDialogForm.warehouseName = this.warehouseList
        .filter((item) => item.warehouseId === id)
        .map((item) => item.warehouseName)
        .join(",");
    },
    getWarehouseData() {
      getWarehouseList({
        page: 1,
        limit: 99999,
      })
        .then((res) => {
          if (!res) return;
          this.warehouseList = res.data;
        })
        .catch((err) => {
          console.log("TCL: getWarehouseList -> err", err);
        });
    },
    onDetail(row) {
      getExtractFindById({ planId: row.planId }).then(({ data }) => {
        this.$router.push({
          path: "/extract-detail",
          query: {
            extractId: data.extractId,
          },
        });
      });
    },
    onExtract(row) {
      this.kuDialogVisible = true;
      this.getWarehouseData();
      this.kuDialogForm.planId = row.planId;
      this.kuDialogForm.planName = row.planName;
    },
    kuDialogSubmit() {
      this.$refs.kuDialogForm.validate(async (valid) => {
        if (valid) {
          this.$router.push({
            name: "extract",
            query: { ...this.kuDialogForm },
          });
          this.kuDialogCancel();
        }
      });
    },
    kuDialogCancel() {
      this.kuDialogVisible = false;
      this.kuDialogForm = {};
      this.$refs.kuDialogForm.resetFields();
    },
    dialogSubmit() {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          postPlanCheck(this.dialogForm).then((res) => {
            if (res) {
              this.getTableData();
              this.ondialogCancel();
            } else {
              this.$message.error("验证失败");
            }
          });
        }
      });
    },
    ondialogCancel() {
      this.dialogVisible = false;
      this.$refs.dialogForm.resetFields();
    },
    onConfirm(row) {
      this.dialogForm.planId = row.planId;
      this.dialogVisible = true;
    },
    onEdit(row) {
      this.form = {
        ...row,
      };
      this.type = "edit";
      this.title = "编辑计划";
      this.drawerVisible = true;
    },
    onAdd() {
      this.form = {};
      this.type = "add";
      this.title = "新增计划";
      this.drawerVisible = true;
    },
    onDelete(row) {
      this.$confirm("您确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        postPlanDel({ planId: row.planId })
          .then(({ success, message }) => {
            if (success) {
              this.$message.success(message);
            } else {
              this.$message.error(message);
            }
            this.getTableData();
          })
          .catch();
      });
    },
    getTableData() {
      this.loading = true;
      this.getTableParams();
      getPlanList(this.tableParams)
        .then((res) => {
          if (!res) return;
          const { data, pageInfo } = res;
          setTimeout(() => {
            this.loading = false;
            this.tableData = data;
            this.total = pageInfo.total;
          }, 500);
        })
        .catch((err) => {
          console.log("TCL: getTableData -> err", err);
        });
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.planId
            ? postPlanUpdate(this.form).then(({ success, message }) => {
                if (success) {
                  this.$message.success(message);
                } else {
                  this.$message.error(message);
                }
                this.onCancel();
                this.form = {};
                this.getTableData();
              })
            : postPlanAdd(this.form).then(({ success, message }) => {
                if (success) {
                  this.$message.success(message);
                } else {
                  this.$message.error(message);
                }
                this.onCancel();
                this.form = {};
                this.getTableData();
              });
        }
      });
    },
    onCancel() {
      this.drawerVisible = false;
      this.$refs.form.resetFields();
    },
  },
};
</script>
